<template>
  <el-dialog
    @click="closed"
    :model-value="modelValue"
    :title="$t('msg.excel.roleDialogTitle')"
  >
    <el-checkbox-group v-model="userRoleTitleList">
      <el-checkbox
        v-for="item in allRoleList"
        :key="item.id"
        :label="item.title"
      >
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closed">
          {{ $t('msg.universal.cancel') }}
        </el-button>
        <el-button type="primary" @click="onConfirm">
          {{ $t('msg.universal.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { getAllRoleList } from '@/api/role'
import { getUserRoles, updateRole } from '@/api/user-manage'
import { watchSwitchLang } from '@/utils/i18n'
import { defineProps, defineEmits, ref, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
const emits = defineEmits(['update:modelValue'])
const i18n = useI18n()
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  userId: {
    type: String,
    required: true
  }
})

watch(
  () => props.userId,
  (val) => {
    if (val) reqUserRoles()
  }
)

// 当前用户角色
const userRoleTitleList = ref([])
// 获取当前用户的角色
const reqUserRoles = async () => {
  const res = await getUserRoles(props.userId)
  console.log('res', res)
  userRoleTitleList.value = res.role.map((item) => item.title)
}
// 所有角色
const allRoleList = ref([])
// 获取所有角色
const getListData = async () => {
  allRoleList.value = await getAllRoleList()
  console.log('🚀 ~ getListData ~ allRoleList.value:', allRoleList.value)
}
watchSwitchLang(getListData)
onMounted(getListData)

const onConfirm = async () => {
  const roles = userRoleTitleList.value.map((title) => {
    return allRoleList.value.find((role) => role.title === title)
  })
  await updateRole(props.userId, roles)
  ElMessage.success(i18n.t('msg.role.updateRoleSuccess'))
  closed()
  emits('updateRole')
}
const closed = () => {
  emits('update:modelValue', false)
}
</script>

<style lang="scss" scoped></style>
